package com.lib.torment.androidlib.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;

import com.lib.torment.androidlib.R;
import com.lib.torment.androidlib.core.AppConfigs;
import com.lib.torment.androidlib.utils.AdapterViewUtils;
import com.lib.torment.androidlib.widget.networkview.EmptyNetWorkView;
import com.lib.torment.androidlib.widget.networkview.ErrorNetWorkView;

import java.util.List;

import static com.lib.torment.androidlib.core.AppConfigs.REFRESH_STATE_INIT;
import static com.lib.torment.androidlib.core.AppConfigs.REFRESH_STATE_REFRESH;

/**
 * 拥有更新当前布局的功能<br/>
 * 加载中<br/>
 * 空数据<br/>
 * 网络错误<br/>
 * 加载更多<br/>
 * Created by Torment on 16-7-15.
 */
public abstract class RefreshAppAdapter<T> extends AppAdapter<T> {

    private static final int PAGE_SIZE = 30;
    protected int mCurrentCounter;

    public RefreshAppAdapter(Context context, int layoutResId, List<T> data) {
        super(context, layoutResId, data, true);
        // 设置加载更多的布局样式
        setLoadingView(setBottomLoadingView());
    }

    // 开启加载更多
    public void openLoadMore(boolean enable) {
        openLoadMore(PAGE_SIZE, true);
    }

    // 获得当前分页的数量
    public int getLoadMoreSize() {
        return PAGE_SIZE;
    }

    public int setNewDatasList(List<T> datas) {
        setNewData(datas);
        removeAllFooterView();
        openLoadMore(PAGE_SIZE, true);
        return PAGE_SIZE;
    }

    public int setLoadingDatas(List<T> data) {
        notifyDataChangedAfterLoadMore(data, true);
        return getData().size();
    }

    /**
     * 加载一张空数据的布局<br/>
     * 其子类只需重写这个方法，做一些自己的业务逻辑
     */
    public void setEmptyDataView() {
        EmptyNetWorkView emptyView = new EmptyNetWorkView(mBaseContext, getEmptyView());
        emptyView.mIconResId = R.mipmap.ic_launcher;
        emptyView.mTitle = mBaseContext.getString(R.string.app_name);
        emptyView.mSubTitle = mBaseContext.getString(R.string.app_name);
        setEmptyView(emptyView);
    }

    /**
     * 加载一张失败的布局<br/>
     * 其子类只需重写这个方法，做一些自己的业务逻辑
     */
    public void setErrorDataView() {
        ErrorNetWorkView newWorkErrorView = new ErrorNetWorkView(mBaseContext, getEmptyView());
        newWorkErrorView.mIconResId = R.mipmap.ic_launcher;
        newWorkErrorView.mTitle = mBaseContext.getString(R.string.app_name);
        newWorkErrorView.mSubTitle = mBaseContext.getString(R.string.app_name);
        setEmptyView(newWorkErrorView);
    }

    /**
     * 加载更多的底部布局<br/>
     * 其子类只需重写这个方法，做一些自己的业务逻辑
     */
    public View setBottomLoadingView() {
        return AdapterViewUtils.setLoadingMoreView(mBaseContext);
    }

    /**
     * 没有更多数据后，在底部显示一个没有更多数据布局
     *
     * @param viewGroup 要传入RecycleView，用于显示底部加载布局
     */
    public View setBottomNoLoadingView(ViewGroup viewGroup) {
        return AdapterViewUtils.setNoLoadingMoreView(mBaseContext, viewGroup);
    }

    /**
     * 设置新数据源，如果数据源为空则显示一个空视图
     *
     * @param newDatas 新数据源
     */
    public int setNewDatasAndUpdateView(List<T> newDatas) {
        if (newDatas == null || newDatas.size() == 0) {
            setEmptyDataView();
        } else {
            mCurrentCounter = setNewDatasList(newDatas);
        }
        return mCurrentCounter;
    }

    /**
     * 设置新数据源，如果数据源为空则显示一个空视图
     *
     * @param newDatas 新数据源
     */
    public int setRefreshDatasAndUpdateView(List<T> newDatas) {
        if (newDatas == null || newDatas.size() == 0) {
            setEmptyDataView();
        }
        mCurrentCounter = setNewDatasList(newDatas);
        return mCurrentCounter;
    }

    /**
     * 加载更多数据，如果数据到底了，则显示一个加载完成的布局
     */
    public int setLoadingDatasAndUpdateView(List<T> newDatas, View view) {
        if (mCurrentCounter == (getData().size() + newDatas.size())) {
            notifyDataChangedAfterLoadMore(false);
            addFooterView(setBottomNoLoadingView((ViewGroup) view.getParent()));
        } else {
            mCurrentCounter = setLoadingDatas(newDatas);
        }
        return mCurrentCounter;
    }

    public void setLoadingError() {
        notifyDataChangedAfterLoadMore(false);
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                mAdapterHandler.sendEmptyMessage(1);
            }
        }.start();
    }

    private Handler mAdapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    // TODO 加载延迟
                    notifyDataChangedAfterLoadMore(true);
                    break;
            }
        }
    };

    class AdapterHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    // TODO 加载延迟

                    notifyDataChangedAfterLoadMore(true);
                    break;
            }
        }
    }

    /**
     * 根据当前的刷新状态去更新ui布局与数据源
     */
    public void refreshUIAccordingToTheCorrectState(int refreshState, List<T> list, View view) {
        switch (refreshState) {
            case AppConfigs.REFRESH_STATE_INIT:
                mCurrentCounter = setNewDatasAndUpdateView(list);
                break;
            case AppConfigs.REFRESH_STATE_REFRESH:
                mCurrentCounter = setRefreshDatasAndUpdateView(list);
                break;
            case AppConfigs.REFRESH_STATE_LOAD:
                mCurrentCounter = setLoadingDatasAndUpdateView(list, view);
                break;
        }
    }

    /**
     * 根据服务器返回的错误去更新ui布局
     */
    public void refreshUIAccordingToTheErrorState(int refreshState) {
        if (refreshState == REFRESH_STATE_INIT) {
            setErrorDataView();
        } else if (refreshState == REFRESH_STATE_REFRESH) {
            if (getData() == null || getData().size() <= 0)
                setErrorDataView();
        } else {
            setLoadingError();
        }
    }
}